package com.example.dyxeapplication.menu.bermain;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Random;

import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.example.dyxeapplication.R;
import com.example.dyxeapplication.menu.Menu;

public class Play_Alfabet_Bermain extends Activity {

	Button btnHome, btnUlangSuara;
	FrameLayout layoutQuiz;
	ArrayList<Item> fullitems = null;
	ArrayList<Item> onLevel = new ArrayList<Item>();
	ImageView answerA, answerB;
	Resources res;
	int resourceId, resId;
	int soal = 0;
	char answer = '-';
	int category = 1;
	Random rand = new Random();
	Context context;
	MediaPlayer mediaPlayer;
	int timepopup = 1500;
	int jumquiz = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu_bermain_huruf);

		initComponent();
		createQuiz(category);

		btnUlangSuara.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mediaPlayer != null)
					mediaPlayer.release();

				playSound(onLevel.get(soal).getSound());

			}
		});
		answerA.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (answer == 'A') {
					customToast("benar");
					new CountDownTimer(timepopup, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
						}

						@Override
						public void onFinish() {
							layoutQuiz.getForeground().setAlpha(0);
							createQuiz(category);
						}
					}.start();
				} else {
					customToast("salah");
					new CountDownTimer(timepopup, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
						}

						@Override
						public void onFinish() {
							layoutQuiz.getForeground().setAlpha(0);
						}
					}.start();
				}

			}
		});
		answerB.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (answer == 'B') {
					customToast("benar");
					new CountDownTimer(timepopup, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
						}

						@Override
						public void onFinish() {
							layoutQuiz.getForeground().setAlpha(0);
							createQuiz(category);
						}
					}.start();
				} else {
					customToast("salah");
					new CountDownTimer(timepopup, 1000) {

						@Override
						public void onTick(long millisUntilFinished) {
						}

						@Override
						public void onFinish() {
							layoutQuiz.getForeground().setAlpha(0);
						}
					}.start();
				}

			}
		});
	}

	private void initComponent() {
		context = getApplicationContext();
		layoutQuiz = (FrameLayout) findViewById(R.id.FrameLayoutQuiz);
		layoutQuiz.getForeground().setAlpha(0);

		res = getApplication().getResources();

		Bundle extras = getIntent().getExtras();
		category = extras.getInt("category_id");

		btnUlangSuara = (Button) findViewById(R.id.buttonUlangSuara);
		answerA = (ImageView) findViewById(R.id.ImageButtonA);
		answerB = (ImageView) findViewById(R.id.ImageButtonB);

		try {
			loadXmlFromAsset();
		} catch (XmlPullParserException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void loadXmlFromAsset() throws XmlPullParserException, IOException {
		AssetManager assetManager = getApplicationContext().getAssets();
		InputStream stream = null;
		ListItemHandler listItemHandler = new ListItemHandler();

		try {
			stream = assetManager.open("listitem_new.xml");
			fullitems = listItemHandler.parse(stream);
		} catch (Exception e) {
			Log.d("ERROR", e.getMessage());
		} finally {
			if (stream != null) {
				stream.close();
			}
		}
	}

	private ArrayList<Item> getAllExceptCategory() {
		ArrayList<Item> onLevel = new ArrayList<Item>();

		for (int i = 0; i < fullitems.size(); i++) {
			if (fullitems.get(i).getHead() != 0
					&& fullitems.get(i).getHead() != 4) {
				onLevel.add(fullitems.get(i));
			}
		}
		return onLevel;
	}

	private void createQuiz(int category) {
		if (jumquiz >= 10) {
			Intent intent = new Intent(this, End_Game_Activity_Huruf.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
		} else {
			onLevel = getAllExceptCategory();

			int count = onLevel.size();

			soal = rand.nextInt(count - 1);

			int wronganswer = 0;
			do {
				wronganswer = rand.nextInt(count - 1);
			} while (onLevel.get(soal).getImage()
					.equals(onLevel.get(wronganswer).getImage()));

			// posisi
			int posisi = rand.nextInt(100);
			if (posisi % 2 != 0) {
				resourceId = res.getIdentifier(onLevel.get(soal).getImage(),
						"drawable", getApplication().getPackageName());
				answerA.setImageResource(resourceId);

				resourceId = res.getIdentifier(onLevel.get(wronganswer)
						.getImage(), "drawable", getApplication()
						.getPackageName());
				answerB.setImageResource(resourceId);
				answer = 'A';
			} else {
				resourceId = res.getIdentifier(onLevel.get(wronganswer)
						.getImage(), "drawable", getApplication()
						.getPackageName());
				answerA.setImageResource(resourceId);

				resourceId = res.getIdentifier(onLevel.get(soal).getImage(),
						"drawable", getApplication().getPackageName());
				answerB.setImageResource(resourceId);
				answer = 'B';
			}

			playSound(onLevel.get(soal).getSound());
			jumquiz++;
		}

	}

	private void playSound(String soundName) {
		AssetFileDescriptor descriptor;
		try {
			if (mediaPlayer != null)
				mediaPlayer.release();

			descriptor = context.getAssets().openFd(
					"sound/" + soundName + ".aac");

			long start = descriptor.getStartOffset();
			long end = descriptor.getLength();
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start,
					end);
			mediaPlayer.prepare();
			mediaPlayer.start();

		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void customToast(String answer) {
		LayoutInflater inflater = (LayoutInflater) Play_Alfabet_Bermain.this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		View layout = inflater.inflate(R.layout.popupquizbener,
				(ViewGroup) findViewById(R.id.popup_element_bener));
		// set a dummy image
		ImageView image = (ImageView) layout.findViewById(R.id.imageAnswerBener);
		if (answer.equalsIgnoreCase("benar")) {
			image.setImageResource(R.drawable.icongreat);
			if (mediaPlayer != null)
				mediaPlayer.release();
			
			mediaPlayer = MediaPlayer.create(this, R.raw.soundbenar);
			mediaPlayer.start();
			Toast toast = new Toast(getApplicationContext());
			// set postion of toast where you want to display
			toast.setGravity(Gravity.FILL, 0, 0);
			// Visible time
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(layout);
			toast.show();
		} else if (answer.equalsIgnoreCase("salah")) {
			image.setImageResource(R.drawable.iconfalse);
			if (mediaPlayer != null)
				mediaPlayer.release();
			
			mediaPlayer = MediaPlayer.create(this, R.raw.soundsalah);
			mediaPlayer.start();
			Toast toast = new Toast(getApplicationContext());
			// set postion of toast where you want to display
			toast.setGravity(Gravity.FILL, 0, 0);
			// Visible time
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(layout);
			toast.show();
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		// Release the MediaPlayer if going into background
		if (mediaPlayer != null)
			mediaPlayer.release();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// Release the MediaPlayer if going into background
		if (mediaPlayer != null)
			mediaPlayer.release();
	}

	public void home(View v) {
		Intent myIntent = new Intent(this, Menu.class);
		myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(myIntent);
	}

}
